﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Mvc.ModelBinding;

namespace MvcApplicationBindersSample.Binders {
    public class VersionModelBinder : IExtensibleModelBinder {

        public bool BindModel(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext) {
            // get value from provider
            ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (vpResult != null) {
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, vpResult);

                // convert to string, then call TryParse() to convert to Version
                string s = (string)vpResult.ConvertTo(typeof(string));
                Version result;
                if (Version.TryParse(s, out result)) {
                    bindingContext.Model = result;
                    return true; // success
                }
                else {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Please enter a valid version number.");
                }
            }

            return false; // failure
        }

    }
}
